#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/base/CountDownLatch.h>
#include <iostream>
#include <unordered_map>
#include <string>

class DictClient
{

public:
    DictClient(const std::string&ip,int port) :
    _baseloop(_loopThread.startLoop()), 
    _client(_baseloop, muduo::net::InetAddress(ip, port), "DictServer"),
    _latch(1)//latch大于0时会阻塞
    {
        _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&DictClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void connect()
    {
        _client.connect();//非阻塞的函数 为了确保链接创建再进行行动所以要等待
        _latch.wait();//类似条件变量 等待信号触发再解除阻塞;
    }
    bool send(std::string& str)
    {
        if(_con->connected())
        {
            _con->send(str);
            return true;
        }
        std::cout<<"connection turn off";
        return false;
    }
    void onConnection(const muduo::net::TcpConnectionPtr &con)
    {
        if (con->connected())
        {
            std::cout << "connected success \n";
            _latch.countDown();//将计数减一 变成0表明连接建立成功了 可以继续运行下去了
            _con=con;
        }
        else
        {
            std::cout << "connected failed \n";
            _con.reset();
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr &con, muduo::net::Buffer *buf, muduo::Timestamp t)
    {
        std::string msg = buf->retrieveAllAsString();
        std::cout << msg << std::endl;
    }

private:
    muduo::net::TcpConnectionPtr _con;
    muduo::net::EventLoopThread _loopThread;
    muduo::net::EventLoop* _baseloop;
    muduo::net::TcpClient _client;
    muduo::CountDownLatch _latch;
};

int main()
{
    DictClient client("127.0.0.1",9090);
    client.connect();
    while(1)
    {
        std::string msg;
        std::cin>>msg;
        if(!client.send(msg))
        {
            return -1;
        }
    }
    return 0;
}